import 'package:common_utils/common_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:x_common_utils/cache_encryption_decrypt_util/cache_encryption_decrypt_util.dart';
import 'package:xinxuan/config/app_config.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/utils/cache_key_util.dart';
import 'package:xinxuan/vo/user_login_vo.dart';
import 'package:xinxuan/vo/verification_vo.dart';

class LoginPageController extends GetxController {

  final CommonPageController commonPageController = Get.find();
  
  /// 是否同意协议
  var isAgreement = false.obs;
  /// 登录类型 0 密码登录，1 验证码登录
  var loginType = 0.obs;
  /// 倒计时总时长
  static int _mTotalTime =  60;
  /// 当前剩余时长
  var duration = _mTotalTime.obs;
  /// 总时长
  int totalDuration = _mTotalTime;
  TimerUtil _timerUtil = TimerUtil(mInterval: 1000, mTotalTime: _mTotalTime * 1000);
  /// 手机号
  var mobile = ''.obs;
  /// 验证码
  var verificationCode = ''.obs;
  /// 密码
  var password = ''.obs;
  /// 确认密码
  var confirmPassword = ''.obs;
  /// 校验手机号
  var checkMobile = true.obs;
  /// 校验验证码
  var checkVerificationCode = true.obs;
  /// 校验密码
  var checkPassword = true.obs;
  /// 明文密码
  var openPassword = true.obs;
  /// 校验确认密码
  var checkConfirmPassword = true.obs;
  /// 验证码Key
  String verificationKey = '';

  /// 第一次校验
  var firstVerification = true.obs;

  /// 重新倒计时
  reCountDown() {
    _timerUtil.cancel();
    _timerUtil.updateTotalTime(_mTotalTime * 1000);
    _timerUtil.setOnTimerTickCallback((int tick) {
      duration.value = (tick ~/ 1000);
      if (tick.toInt() <= 0) {
        _timerUtil.updateTotalTime(_mTotalTime * 1000);
        _timerUtil.cancel();
      }
    });
    if (duration.value >= _mTotalTime) {
      _timerUtil.startCountDown();
    }
  }

  /// 校验手机号
  checkMobileFun() {
    // if (!RegexUtil.isMobileExact(mobile)) {
    //   checkMobile.value = false;
    //   return false;
    // }
    firstVerification.value = false;
    if (mobile.value.length < 11 || mobile.substring(0, 1) != '1') {
      checkMobile.value = false;
      return false;
    }
    checkMobile.value = true;
    return true;
  }

  /// 校验验证码
  _checkVerificationCode() {
    if (TextUtil.isEmpty(verificationCode.value) || verificationCode.value.length < 6) {
      checkVerificationCode.value = false;
      return false;
    }
    checkVerificationCode.value = true;
    return true;
  }

  /// 校验密码
  _checkPassword() {
    if (TextUtil.isEmpty(password.value)) {
      checkPassword.value = false;
      return false;
    }
    checkPassword.value = true;
    return true;
  }

  /// 校验修改密码
  checkUpdatePassword() {
    var _regExp=r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,11}$';
    if (!RegExp(_regExp).hasMatch(password.value)) {
      checkPassword.value = false;
      return false;
    }
    checkPassword.value = true;
    return true;
  }

  /// 校验确认密码
  checkConfirmPasswordFun() {
    if (TextUtil.isEmpty(confirmPassword.value) || password.value != confirmPassword.value) {
      checkConfirmPassword.value = false;
      return false;
    }
    checkConfirmPassword.value = true;
    return true;
  }

  _checkAgreement() {
    if (!isAgreement.value) {
      EasyLoading.showToast('请同意隐私政策以及用户协议');
      return false;
    }
    return true;
  }

  /// 校验并获取验证码
  checkAndGetCode() async {
    if (!checkMobileFun()) {
      return;
    }
    if (!_checkAgreement()) {
      return;
    }
    getSmsCode('login');
  }

  /// 获取验证码
  Future<VerificationVo?> getSmsCode(String type) async {
    VerificationVo? res = await HttpUtilService.getVerificationCode(mobile: mobile.value, type: type);
    if (res != null) {
      verificationKey = res.data!.verificationKey!;
      EasyLoading.showToast('发送成功');
      reCountDown();
      return res;
    }
    return null;
  }

  /// 验证码登录
  verificationCodeLogin() async {
    if (!checkMobileFun()) {
      return;
    }
    if (!_checkAgreement()) {
      return;
    }
    if (!_checkVerificationCode()) {
      return;
    }
    UserLoginVo userLoginVo = await HttpUtilService.verificationCodeLogin(mobile: mobile.value, verificationCode: verificationCode.value, verificationKey: verificationKey);
    _loginSuccess('${userLoginVo.meta!.accessToken}');
  }

  /// 密码
  passwordLogin() async {
    if (!checkMobileFun()) {
      return;
    }
    if (!_checkAgreement()) {
      return;
    }
    if (!_checkPassword()) {
      return;
    }
    UserLoginVo userLoginVo = await HttpUtilService.passwordLogin(mobile: mobile.value, password: password.value);
    _loginSuccess('${userLoginVo.meta!.accessToken}');
  }

  /// 登录成功后操作
  _loginSuccess(String token) async {
    AppConfig.token = token;
    await CacheEncryptionDecryptUtil.saveStringCacheEncryption(key: CacheKeyUtil.token, value: token);
    commonPageController.openSignFun.value = 0;
    await commonPageController.checkLogin();
    Get.back();
  }

  /// 修改密码
  editPassword() async {
    if (!checkUpdatePassword()) {
      return;
    }
    if (!checkConfirmPasswordFun()) {
      return;
    }
    if (!_checkVerificationCode()) {
      return;
    }
    bool res = await HttpUtilService.editPassword(verificationCode: verificationCode.value, password: password.value, verificationKey: verificationKey);
    if (res) {
      Get.back();
      EasyLoading.showToast('修改成功');
    }
  }

  @override
  void dispose() {
    _timerUtil.cancel();
    super.dispose();
  }
}